package com.young.shop_admin.controller;

import com.young.shop_admin.pojo.entity.Goods;
import com.young.shop_admin.pojo.entity.Page;
import com.young.shop_admin.services.GoodsService;
import com.young.shop_admin.services.impl.GoodsServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

/**
 *
 */
@WebServlet("/findGoodsByPage")
public class FindGoodsByPageController extends BaseController{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //由于是显示所有的产品信息,没有参数接收
        //需要调用服务层查找所有数据的方法,获取结果,响应给客户端
        //调用service查询
        GoodsService goodsServiceImpl = new GoodsServiceImpl();
        //解决跨域问题
        resp.setHeader("Access-Control-Allow-Origin","http://localhost:63342");
        //1.获取参数
        //当前页码
        int currentPage = Integer.parseInt(req.getParameter("currentPage"));
        //每页显示条数
        int pageSize = Integer.parseInt(req.getParameter("pageSize"));

        String searchByType = req.getParameter("searchByType");



        try {
            Page page = goodsServiceImpl.findPageInfo(currentPage,pageSize,searchByType);
            //把数据转为json
            //String jsonString = JSONObject.toJSONString(page);
            //回写给浏览器



            //resp.getWriter().write(jsonString);
            if (page == null) {
                List<Goods> allGoods = goodsServiceImpl.findAllGoods();
                writerSuccessResult(allGoods,resp);
                return;
            }
            System.out.println(page);
            writerSuccessResult(page,resp);

            //System.out.println(jsonString);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }
}
